package app.config;


import app.core.admin.Admins;
import cn.dev33.satoken.fun.strategy.SaCorsHandleFunction;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpInterface;
import com.gitee.feizns.dynamic.Nums;
import com.gitee.feizns.quickstart.web.cross.Cross;
import com.gitee.feizns.quickstart.web.spring.boot.autoconfigure.QuickstartWebProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @author feizns
 * @since 2025/8/9
 */
@Component
@RequiredArgsConstructor
public class SaTokenConfigure implements StpInterface {

    /**
     * web配置
     */
    private final QuickstartWebProperties properties;

    /**
     * CORS 跨域处理策略
     */
    @Bean
    public SaCorsHandleFunction corsHandle() {
        Cross cross = properties.getCross();
        return (req, res, sto) -> {
            res.setHeader("Access-Control-Allow-Origin", String.join(",", cross.getAllowOrigins()));
            // 允许所有请求方式
            res.setHeader("Access-Control-Allow-Methods", String.join(",", cross.getAllowMethods()));
            // 允许的header参数
            res.setHeader("Access-Control-Allow-Headers", String.join(",", cross.getAllowHeaders()));
            // 如果是预检请求，则立即返回到前端
            SaRouter.match(SaHttpMethod.OPTIONS).free(r -> System.out.println("OPTIONS预检请求，不做处理")).back();
        };
    }

    @Override
    public List<String> getPermissionList(Object id, String type) {
        return Admins.menuIdentifiers(Nums.of(id).longValue());
    }

    @Override
    public List<String> getRoleList(Object id, String type) {
        return Admins.roleIds().stream().map(Objects::toString).toList();
    }

}
